package com.frankle.mybatisplusgenerator.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropUtil {
	private static Logger logger = LoggerFactory.getLogger(PropUtil.class);

	private static Properties props;
	
	private static PropUtil propUtil = new PropUtil();
	
	private static String file;

	private PropUtil() {}
	
	public static PropUtil use(String fileName) {
		propUtil.readProperties(fileName);
		file = fileName;
		return propUtil;
	}

	/**
	 * 加载配置文件
	 * @param fileName
	 */
	private  void readProperties(String fileName) {
		try {
			props = new Properties();
			InputStreamReader inputStream = new InputStreamReader(
					this.getClass().getClassLoader().getResourceAsStream(fileName), "UTF-8");
			props.load(inputStream);
		} catch (Exception e) {
			logger.error("加载文件异常",e);
		}
	}

	/**
	 * 根据key读取对应的value
	 * 
	 * @param key
	 * @return
	 */
	public String get(String key) {
		return props.getProperty(key);
	}

	/**
	 * 得到所有的配置信息
	 * 
	 * @return
	 */
	public Map<?, ?> getAll() {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<?> enu = props.propertyNames();
		while (enu.hasMoreElements()) {
			String key = (String) enu.nextElement();
			String value = props.getProperty(key);
			map.put(key, value);
		}
		return map;
	}
	
	public void set(String key, String value) {
		props.setProperty(key, value);
	}
	
	public void save() {
		try {
			props.store(new FileOutputStream(file, false), "");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
